package top.yoohome.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.util.List;

/**
 * 对象拷贝工具类
 * 
 * @author Johnny Zhang
 */
public class ObjectCopyUtil {

    /** 统一处理时间格式 */
    private static final String DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 对象拷贝->List对象
     *
     * @param sourceObject 源拷贝对象
     * @param targetClazz 反射目标对象
     * @return List<T> List对象
     */
    public static <T> List<T> copy(Iterable sourceObject, Class<T> targetClazz) {
        if (sourceObject == null) {
            return null;
        }
        JSON.DEFFAULT_DATE_FORMAT = DEFFAULT_DATE_FORMAT;
        return JSON.parseArray(JSON.toJSONString(sourceObject, SerializerFeature.DisableCircularReferenceDetect,
            SerializerFeature.WriteDateUseDateFormat), targetClazz);
    }

    /**
     * 对象拷贝->泛型对象
     *
     * @param sourceObject 源拷贝对象
     * @param targetClazz 反射目标对象
     * @return T 泛型对象
     */
    public static <T> T copy(Object sourceObject, Class<T> targetClazz) {
        if (sourceObject == null) {
            return null;
        }
        JSON.DEFFAULT_DATE_FORMAT = DEFFAULT_DATE_FORMAT;
        return JSON.parseObject(JSON.toJSONString(sourceObject, SerializerFeature.DisableCircularReferenceDetect,
            SerializerFeature.WriteDateUseDateFormat), targetClazz);
    }
}